import { defineStore } from 'pinia'
import { setItem, getItem } from '@/utils/storage'
import { LANG, MAIN_COLOR, DEFAULT_COLOR, TAGS_VIEW } from '@/contant'
import { generateColor } from '@/utils/theme'
import variables from '@/assets/styles/variables.scss'

export const useAppStore = defineStore('app', {
  state: () => ({
    sidebarOpened: true,
    language: getItem(LANG) || 'zh',
    mainColor: getItem(MAIN_COLOR) || DEFAULT_COLOR,
    variables, // 主题色变量
    tagsViewList: getItem(TAGS_VIEW) || []
  }),
  getters: {
    cssVar: (state) => ({
      ...state.variables,
      ...generateColor(getItem(MAIN_COLOR))
    })
  },
  actions: {
    // 触发menu表表的展开收起
    triggerSidebarOpened() {
      this.sidebarOpened = !this.sidebarOpened
    },
    // 设置语言
    setLanguage(lang) {
      setItem(LANG, lang)
      this.language = lang
    },
    // 设置默认颜色
    setMainColor(color) {
      setItem(MAIN_COLOR, color)
      this.mainColor = color
      this.variables.menuBg = color
    },
    addTagsViewList(tag) {
      // 先判断是否已经存在tag，如果存在则不添加(去重的效果)
      const isFind = this.tagsViewList.find((item) => item.path === tag.path)
      if (!isFind) {
        this.tagsViewList.push(tag)
        setItem(TAGS_VIEW, this.tagsViewList)
      }
    },
    removeTagsView({ type, index }) {
      if (type == 'index') {
        this.tagsViewList.splice(index, 1)
      } else if (type == 'right') {
        this.tagsViewList.splice(index + 1)
      } else if (type == 'other') {
        this.tagsViewList.splice(index + 1) // 删除右侧
        this.tagsViewList.splice(0, index) // 删除左侧
      }

      setItem(TAGS_VIEW, this.tagsViewList)
    }
  }
})
